package eip.chapter5.sequence.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.JiBXException;

import eip.chapter5.sequence.Bill;
import eip.chapter5.sequence.CheckoutBill;

public class JiBXHelper {

	private static IBindingFactory billfact;
	private static IBindingFactory checkoutfact;
	
	private static IBindingFactory getBillFactory() throws JiBXException {
		if(billfact == null) {
			billfact = BindingDirectory.getFactory(Bill.class);
		}
		return billfact;
	}
	
	private static IBindingFactory getCheckoutBillFactory() throws JiBXException {
		if(checkoutfact == null) {
			checkoutfact = BindingDirectory.getFactory(CheckoutBill.class);
		}
		return checkoutfact;
	}
	
	public static String createBillinXML(Bill bill) throws JiBXException {
		StringWriter writer = new StringWriter();
		getBillFactory().createMarshallingContext().marshalDocument(bill, "UTF-8", null, writer);
		return writer.toString();
	}
	
	public static Bill createBillFromXML(TextMessage billMessage) throws JiBXException, JMSException {
		return (Bill) getBillFactory().createUnmarshallingContext().
				unmarshalDocument(new StringReader(billMessage.getText()), null);
	}
	
	public static String createCheckoutBillinXML(CheckoutBill checkoutBill) throws JiBXException {
		StringWriter writer = new StringWriter();
		getCheckoutBillFactory().createMarshallingContext().marshalDocument(checkoutBill, "UTF-8", null, writer);
		return writer.toString();
	}
	
	public static CheckoutBill createCheckoutBillFromXML(String message) throws JiBXException {
		return (CheckoutBill) getCheckoutBillFactory().createUnmarshallingContext().
			unmarshalDocument(new StringReader(message), null);
	}
	
}
